import { reqCartList } from "@/api"
import { reqDeleteCartById } from "@/api"
import { reqUpdateCheckedById } from "@/api"



//search模块的小仓库
const state = {
    cartList: []

}

const actions = {
    //获取购物车列表的数据
    async getCartList({ commit }) {
        let result = await reqCartList()
        if (result.code == 200) {
            commit('GETCARTLIST', result.data)
        }
    },
    //删除购物车某一个产品
    async deleteCartListBySkuId({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //修改购物车某一个产品的选中状态
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedById(skuId, isChecked)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //删除全部勾选的产品
    deleteAllCheckedCart({dispatch, getters}){
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item=>{
            let promise = item.isChecked==1?dispatch('deleteCartListBySkuId', item.skuId):''
            //将每一次返回的Promise添加到数组中
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    },
    //修改全部产品的状态
    updateAllCartIsChecked({dispatch, state}, isChecked){
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach(item=>{
            let promise = item.isChecked!=isChecked?dispatch('updateCheckedById', { skuId:item.skuId, isChecked }):''
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    },

}

const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList
    }

}

//简化仓库中的数据
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    },


}

export default {
    state,
    mutations,
    actions,
    getters
}